package com.flowable.service;

import com.flowable.entity.LeaveRequest;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LeaveService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * 提交请假申请
     */
    public String submitLeaveRequest(LeaveRequest leaveRequest) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("applicant", leaveRequest.getApplicant());
        variables.put("reason", leaveRequest.getReason());
        variables.put("days", leaveRequest.getDays());
        variables.put("startDate", leaveRequest.getStartDate());
        variables.put("endDate", leaveRequest.getEndDate());

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leave-approval", variables);
        
        // 完成申请任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        if (task != null) {
            taskService.complete(task.getId());
        }

        return processInstance.getId();
    }

    /**
     * 查询待审批的任务（领导）
     */
    public List<Task> getManagerTasks() {
        return taskService.createTaskQuery()
                .taskCandidateGroup("manager")
                .list();
    }

    /**
     * 查询待审批的任务（老板）
     */
    public List<Task> getBossTasks() {
        return taskService.createTaskQuery()
                .taskCandidateGroup("boss")
                .list();
    }

    /**
     * 领导审批
     */
    public void managerApproval(String taskId, String approvalResult, String comment) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approvalResult", approvalResult);
        variables.put("comment", comment);

        System.err.println(variables);
        taskService.complete(taskId, variables);
    }

    /**
     * 老板审批
     */
    public void bossApproval(String taskId, String approvalResult, String comment) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approvalResult", approvalResult);
        variables.put("comment", comment);
        taskService.complete(taskId, variables);
    }

    /**
     * 获取任务详情
     */
    public Map<String, Object> getTaskDetails(String taskId) {
        return taskService.getVariables(taskId);
    }

    /**
     * 查询流程历史
     */
    public List<String> getProcessHistory(String processInstanceId) {
        List<HistoricActivityInstance> activities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .asc()
                .list();

        return activities.stream()
                .map(activity -> String.format("活动名称: %s, 执行时间: %d毫秒", 
                        activity.getActivityName(), 
                        activity.getDurationInMillis()))
                .collect(Collectors.toList());
    }

    /**
     * 获取所有运行中的流程实例
     */
    public List<ProcessInstance> getRunningProcesses() {
        return runtimeService.createProcessInstanceQuery()
//                .processDefinitionKey("leave-approval")
                .list();
    }

    /**
     * 根据申请人查询流程实例
     */
    public List<ProcessInstance> getProcessesByApplicant(String applicant) {
        return runtimeService.createProcessInstanceQuery()
                .processDefinitionKey("leave-approval")
                .variableValueEquals("applicant", applicant)
                .list();
    }
}